<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
   <canvas id="canvasgl" width="800" height="600">
       your browser don't support canvas
   </canvas> 

    <script src="../lib/webgl-utils.js"></script>
    <script src="../lib/webgl-debug.js"></script>
    <script src="../lib/cuon-utils.js"></script>
    <script src="../lib/cuon-matrix.js"></script>

    <script>
      var VSHADER_SOURCE = `
              attribute vec4 a_Position;
              attribute vec4 a_Color;
              varying vec4 v_Color;

              void main(){
                  gl_Position = a_Position;
                  gl_PointSize = 10.0;
                  v_Color = a_Color;
              }
          `;

      var FSHADER_SOURCE = `
              precision mediump float;
              varying vec4 v_Color;

              void main(){
                  gl_FragColor = v_Color;
              }
          `;

      var canvas = document.getElementById("canvasgl");
      var gl = getWebGLContext(canvas);
      if (!gl) throw new Error("can't get webgl context");

      if (!initShaders(gl, VSHADER_SOURCE, FSHADER_SOURCE)) {
        throw new Error("can't init shaders");
      }

      var n = initVertextBuffers(gl);
      if (n < 0) throw new Error("failed set positions of vertices");


      gl.clearColor(0.0, 0.0, 0.0, 1.0);
      gl.clear(gl.COLOR_BUFFER_BIT);
      gl.drawArrays(gl.TRIANGLES, 0, n);

      function initVertextBuffers(gl) {
        var verticesColors = new Float32Array([
            0.0, 0.5, 1.0, 0.0, 0.0,
            -0.5, -0.5, 0.0, 1.0, 0.0, 
            0.5, -0.5, 0.0, 0.0, 1.0
        ]);
        var n = 3;

        var vertexColorBuffer = gl.createBuffer();
        if (!vertexColorBuffer) throw new Error("can't init vertext buffet");
        gl.bindBuffer(gl.ARRAY_BUFFER, vertexColorBuffer);
        gl.bufferData(gl.ARRAY_BUFFER, verticesColors, gl.STATIC_DRAW);

        var FSIZE = verticesColors.BYTES_PER_ELEMENT;
        var a_Position = gl.getAttribLocation(gl.program, 'a_Position');
        gl.vertexAttribPointer(a_Position, 2, gl.FLOAT, false, FSIZE * 5, 0);
        gl.enableVertexAttribArray(a_Position);

        var a_Color = gl.getAttribLocation(gl.program, 'a_Color');
        gl.vertexAttribPointer(a_Color, 3, gl.FLOAT, false, FSIZE * 5, FSIZE * 2);
        gl.enableVertexAttribArray(a_Color);
        
        return n;
      }
    </script>
</body>
</html>